package com.sdkj.fixed.asset.assets.service;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.PageHelper;
import com.sdkj.fixed.asset.api.assets.in_vo.*;
import com.sdkj.fixed.asset.api.assets.out_vo.*;
import com.sdkj.fixed.asset.api.login.out_vo.CompanyBaseListResult;
import com.sdkj.fixed.asset.api.login.pojo.LoginRole;
import com.sdkj.fixed.asset.api.login.pojo.LoginUser;
import com.sdkj.fixed.asset.assets.mapper.*;
import com.sdkj.fixed.asset.assets.util.CacheUtils;
import com.sdkj.fixed.asset.assets.util.DateTools;
import com.sdkj.fixed.asset.assets.util.ExcelUtils;
import com.sdkj.fixed.asset.common.base.PageParams;
import com.sdkj.fixed.asset.common.utils.TimeTool;
import com.sdkj.fixed.asset.pojo.assets.AssetLog;
import com.sdkj.fixed.asset.pojo.assets.AssetReport;
import com.sdkj.fixed.asset.pojo.assets.Warehouse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author zhangjinfei
 * @Description //TODO 资产使用情况统计
 * @Date 2020/8/10 11:10
 */
@Service
public class AssetReportService {

    @Autowired
    private AssetReportMapper mapper;
    @Autowired
    private WarehouseMapper warehouseMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private CacheUtils cacheUtils;
    @Autowired
    private ScrapMapper scrapMapper;
    @Autowired
    private WarehouseService warehouseService;
    @Autowired
    private HttpServletResponse response;
    @Autowired
    private BorrowIssueMapper borrowIssueMapper;
    @Autowired
    private AssetLogMapper logMapper;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WarehouseHistoryMapper historyMapper;
    /**
     *  使用人ID  资产ID
     * @param assetReport
     */
    public void insertReport(AssetReport assetReport){
        String token = request.getHeader("token");
        // redis 查询用户权限： 如果是管理员为false 查询全部
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        List<CompanyBaseListResult> companys = loginUser.getCompanys();
        String orgId = companys.get(0).getCompanyId();
        Warehouse warehouse = warehouseMapper.selectByPrimaryKey(assetReport.getAssetId());
        assetReport.setAmount(warehouse.getAmount());
        assetReport.setUseCompany(warehouse.getUseCompany());
        assetReport.setOrgId(orgId);
        assetReport.setCreateUser(userId);
        assetReport.setCreateTime(DateTools.nowDate());
        mapper.insertSelective(assetReport);
    }

    /**
     * 标准型号
     * @param name
     * @return
     */
    public List<StandardModelReport> standardModelReport( String token ,String name){
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String orgId = cacheUtils.getUserCompanyId(token);
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        List<StandardModelReport> list= mapper.standardModelReport(userId,orgId,name);
        return  list;
    }

    /**
     * 清理清理-分页查询
     * @param param
     * @return
     */
    public List<AssetsReportResult> queryScrapPage(PageParams<SelPrams> param){
        String orgId = request.getHeader("orgId");
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        PageHelper.startPage(param.getCurrentPage(), param.getPerPageTotal());
        List<AssetsReportResult> list = mapper.queryAllScrap(param.getParams().getStartDate(), param.getParams().getEndDate(), orgId, userId);
        return list;
    }

    /**
     * 清理清理导出
     * @param startDate
     * @param endDate
     * @throws IOException
     */
    public void exportScrap(String startDate, String endDate, String orgId, String token) throws IOException {
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        List<AssetsReportResult> list = mapper.queryAllScrap(startDate, endDate, orgId, userId);
        ExcelUtils.exportExcel(list, AssetsReportResult.class, "清理清单"+ TimeTool.getCurrentTimeStr(),  response);
    }

    /**
     * 员工资产统计
     * @return
     */
    public List<UserInfo> userAssetInfo(PageParams<UserAssetSelParam> params){
        String token = request.getHeader("token");
        String orgId = request.getHeader("orgId");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        List<UserInfo> list = mapper.userInfo(orgId, userId, params.getParams().getSearch(), params.getParams().getIsOnJob());

        for (UserInfo e:list) {
            System.out.println(e.getName());
            List<WarehouseResult> userAssetList = new ArrayList<>();
            List<BorrowIssueExtend> borrowList = new ArrayList<>();
            List<WarehouseResult> warehouseResultList = warehouseService.getAllByUserId(e.getId(), orgId, loginUser.getUserId());

            warehouseResultList.stream().forEach(e1->{

                if(e.getId().equals(e1.getHandlerUserId()) && (e1.getState().equals("在用") || e1.getState().equals("退库中")
                        || e1.getState().equals("报修中") || e1.getState().equals("维修中") || e1.getState().equals("调拨中"))){
                    userAssetList.add(e1);
                }
                if(e.getId().equals(e1.getHandlerUserId()) && (e1.getState().equals("借用"))){
                    BorrowIssueExtend extend = borrowIssueMapper.selByAssetId(e1.getAssetId());
                    if(extend != null){
                        List<WarehouseHistoryResult> resList = new ArrayList<>();
                        WarehouseHistoryResult result = new WarehouseHistoryResult();
                        BeanUtil.copyProperties(e1, result);
                        extend.setResults(resList);
                        resList.add(result);
                        borrowList.add(extend);
                    }
                }
            });
            e.setUserAssetList(userAssetList);
            e.setBorrowList(borrowList);
        }

        Iterator<UserInfo> it = list.iterator();
        while(it.hasNext()){
            UserInfo info = it.next();
            if(CollectionUtils.isEmpty(info.getUserAssetList()) && CollectionUtils.isEmpty(info.getBorrowList())){
                it.remove();
            }
        }
        return list;
    }

    /**
     * 员工统计导出
     * @param search
     * @param isOnJob
     * @param orgId
     * @param token
     * @throws IOException
     */
    public void exportUserAssetInfo(String search, String isOnJob, String orgId, String token) throws IOException {
        List<ExportUserReport> list = new ArrayList<>();
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        List<UserInfo> list1 = mapper.userInfo(orgId, userId, search, isOnJob);

        list1.stream().forEach(e->{
            List<WarehouseResult> warehouseResultList = warehouseService.getAllByUserId(e.getId(), orgId, loginUser.getUserId());
            warehouseResultList.stream().forEach(e1->{
                if(e.getId().equals(e1.getHandlerUserId()) && (e1.getState().equals("在用") || e1.getState().equals("退库中")
                        || e1.getState().equals("报修中") || e1.getState().equals("维修中") || e1.getState().equals("调拨中"))){
                    ExportUserReport report = new ExportUserReport();
                    report.setEmployeeId(e.getEmployeeId());
                    report.setName(e.getName());
                    report.setCompanyName(e.getCompanyName());
                    report.setDeptName(e.getDeptName());
                    report.setTel(e.getTel());
                    report.setEmail(e.getEmail());
                    report.setUseModel("领用");
                    report.setNumber("");
                    report.setLendDate("");
                    report.setAssetCode(e1.getAssetCode());
                    report.setAssetName(e1.getAssetName());
                    report.setAssetClassName(e1.getAssetClassName());
                    report.setSpecificationModel(e1.getSpecificationModel());
                    report.setSnNumber(e1.getSnNumber());
                    report.setAmount(e1.getAmount());
                    report.setUseCompanyName(e1.getUseCompanyName());
                    report.setUseDeptName(e1.getUseDeptName());
                    report.setHandlerUser(e1.getHandlerUser());
                    report.setAdmin(e1.getAdmin());
                    report.setAssetCompanyName(e1.getCompanyName());
                    report.setAreaName(e1.getAreaName());
                    report.setStorageLocation(e1.getStorageLocation());
                    list.add(report);
                }
                if(e.getId().equals(e1.getHandlerUserId()) && (e1.getState().equals("借用"))){
                    BorrowIssueExtend extend = borrowIssueMapper.selByAssetId(e1.getAssetId());
                    if(extend != null){
                        ExportUserReport report = new ExportUserReport();
                        report.setEmployeeId(e.getEmployeeId());
                        report.setName(e.getName());
                        report.setCompanyName(e.getCompanyName());
                        report.setDeptName(e.getDeptName());
                        report.setTel(e.getTel());
                        report.setEmail(e.getEmail());
                        report.setUseModel("借用");
                        report.setNumber(extend.getNumber());
                        report.setLendDate(extend.getLendDate());
                        report.setAssetCode(e1.getAssetCode());
                        report.setAssetName(e1.getAssetName());
                        report.setAssetClassName(e1.getAssetClassName());
                        report.setSpecificationModel(e1.getSpecificationModel());
                        report.setSnNumber(e1.getSnNumber());
                        report.setAmount(e1.getAmount());
                        report.setUseCompanyName(e1.getUseCompanyName());
                        report.setUseDeptName(e1.getUseDeptName());
                        report.setHandlerUser(e1.getHandlerUser());
                        report.setAdmin(e1.getAdmin());
                        report.setAssetCompanyName(e1.getCompanyName());
                        report.setAreaName(e1.getAreaName());
                        report.setStorageLocation(e1.getStorageLocation());
                        list.add(report);
                    }
                }
            });
        });
        ExcelUtils.exportExcel(list, ExportUserReport.class, "员工资产统计"+ TimeTool.getCurrentTimeStr(),  response);
    }

    /**
     *  到期资产
     *  月增加队长表
     * @param params
     * @return
     */
    public List<AssetsReportResult>  assetsReport(PageParams<WarehouseReportParam> params){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String orgId = cacheUtils.getUserCompanyId(token);
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        WarehouseReportParam param = params.getParams();
        param.setUserId(userId);
        param.setOrgId(orgId);

        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        List<AssetsReportResult> list= mapper.assetsReport(param);
        return  list;
    }

    public List<AssetsReportResult> exportAssetsReport(String token, WarehouseReportParam param) {
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String orgId = cacheUtils.getUserCompanyId(token);
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        param.setUserId(userId);
        param.setOrgId(orgId);
        List<AssetsReportResult> list= mapper.assetsReport(param);
        return  list;
    }

    public DueAssetsRecord dueAssetsReportRecord(String assetId) {
        DueAssetsRecord dr = mapper.dueAssetsReportRecord(assetId);
        return  dr;
    }

    public List<AssetLog> dueAssetsReportRecordLog(PageParams<AssetIdParam> params) {
        PageHelper.startPage(params.getCurrentPage(), params.getPerPageTotal());
        AssetIdParam param = params.getParams();
        List<AssetLog> list= logMapper.queryLogByAssetId(param.getAssetId());
        return  list;
    }

    public List<CompanyReport> companyDeptReport(ClassIdParam param) {
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String orgId = cacheUtils.getUserCompanyId(token);
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        param.setUserId(userId);
        param.setOrgId(orgId);
        List<CompanyReport> reportList = mapper.companyDeptReport(param);

        for (int i = 0; i < reportList.size() ; i++) {
            CompanyReport companyReport = reportList.get(i);
            if(companyReport.getType()==2){ // 如果是部门不需要累加
                continue;
            }
            Integer level = companyReport.getTreecode().split(",").length + 1;
            companyReport.setLevel(level.toString());
            Integer totalCount = companyReport.getCount();
            BigDecimal totalAmount = new BigDecimal(companyReport.getTotalAmount());
            for (CompanyReport cr : reportList) {
                if(cr.getType()==2){ // 如果是部门不需要累加
                    continue;
                }
                String  treecode = cr.getTreecode();
                Integer count = cr.getCount()== null ? 0 : cr.getCount();
                String  amount = cr.getTotalAmount()== null ? "0" : cr.getTotalAmount();
                if (!companyReport.getId().equals(cr.getId()) && treecode.contains(companyReport.getTreecode())){
                    totalCount += count;
                    totalAmount = totalAmount.add(new BigDecimal(amount));
                }
            }
            companyReport.setCount(totalCount);
            companyReport.setTotalAmount(totalAmount.setScale(2, RoundingMode.HALF_UP).toString());
        }
        return  reportList;
    }


    public List<CompanyReport> exportCompanyDeptReport(String token, String classId) {
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String orgId = cacheUtils.getUserCompanyId(token);
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        ClassIdParam param = new ClassIdParam();
        param.setUserId(userId);
        param.setOrgId(orgId);
        param.setClassId(classId);
        List<CompanyReport> reportList = mapper.companyDeptReport(param);
        for (int i = 0; i < reportList.size() ; i++) {
            CompanyReport companyReport = reportList.get(i);
            if(companyReport.getType()==2){ // 如果是部门不需要累加
                continue;
            }
            Integer level = companyReport.getTreecode().split(",").length + 1;
            companyReport.setLevel(level.toString());
            Integer totalCount = companyReport.getCount();
            BigDecimal totalAmount = new BigDecimal(companyReport.getTotalAmount());
            for (CompanyReport cr : reportList) {
                if(cr.getType()==2){ // 如果是部门不需要累加
                    continue;
                }
                String  treecode = cr.getTreecode();
                Integer count = cr.getCount()== null ? 0 : cr.getCount();
                String  amount = cr.getTotalAmount()== null ? "0" : cr.getTotalAmount();
                if (!companyReport.getId().equals(cr.getId()) && treecode.contains(companyReport.getTreecode())){
                    totalCount += count;
                    totalAmount = totalAmount.add(new BigDecimal(amount));
                }
            }
            companyReport.setCount(totalCount);
            companyReport.setTotalAmount(totalAmount.setScale(2, RoundingMode.HALF_UP).toString());
        }
        return  reportList;
    }

    public List<UseClassReport> useClassReport(CompanyDeptParam param) {
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String orgId = cacheUtils.getUserCompanyId(token);
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        param.setUserId(userId);
        param.setOrgId(orgId);
        List<UseClassReport> reportList = mapper.useClassReport(param);
        for (int i = 0 ; i < reportList.size() ; i++) {
            UseClassReport useClassReport = reportList.get(i);
            Integer level = useClassReport.getTreecode().split(",").length + 1;
            useClassReport.setLevel(level.toString());
            Integer inUse = 0;
            //    闲置
            Integer idle = 0;
            //    待发放
            Integer give = 0;
            //    借用
            Integer borrow = 0;
            //    已报废
            Integer scrapped = 0;
            //    调拨中
            Integer transfer = 0;
            //    维修中
            Integer repair = 0;
            //    总计
            Integer total = 0;
            for (UseClassReport ucr : reportList) {
                ucr.setInUse(ucr.getInUse()==null? 0 : ucr.getInUse());
                ucr.setIdle(ucr.getIdle()==null? 0 : ucr.getIdle());
                ucr.setGive(ucr.getGive()==null? 0 : ucr.getGive());
                ucr.setBorrow(ucr.getBorrow()==null? 0 : ucr.getBorrow());
                ucr.setScrapped(ucr.getScrapped()==null? 0 : ucr.getScrapped());
                ucr.setTransfer(ucr.getTransfer()==null? 0 : ucr.getTransfer());
                ucr.setRepair(ucr.getRepair()==null? 0 : ucr.getRepair());
                ucr.setTotal(ucr.getTotal()==null? 0 : ucr.getTotal());
                String  treecode = ucr.getTreecode();

                //如果是根节点到子节点相加
                if (treecode.contains(useClassReport.getId())){
                    inUse += ucr.getInUse();
                    //    闲置
                    idle += ucr.getIdle();
                    //    待发放
                    give += ucr.getGive();
                    //    借用
                    borrow += ucr.getBorrow();
                    //    已报废
                    scrapped += ucr.getScrapped();
                    //    调拨中
                    transfer += ucr.getTransfer();
                    //    维修中
                    repair += ucr.getRepair();
                    //    总计
                    total += ucr.getTotal();
                    continue;
                }
            }
            useClassReport.setInUse(inUse);
            useClassReport.setIdle(idle);
            useClassReport.setGive(give);
            useClassReport.setBorrow(borrow);
            useClassReport.setScrapped(scrapped);
            useClassReport.setTransfer(transfer);
            useClassReport.setRepair(repair);
            useClassReport.setTotal(total);
        }
        return  reportList;
    }

    public List<UseClassReport> exportUseClassReport(String token,CompanyDeptParam param) {
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String orgId = cacheUtils.getUserCompanyId(token);
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        param.setUserId(userId);
        param.setOrgId(orgId);
        List<UseClassReport> reportList = mapper.useClassReport(param);
        for (int i=0; i < reportList.size(); i++) {
            UseClassReport useClassReport = reportList.get(i);
            Integer level = useClassReport.getTreecode().split(",").length + 1;
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < level; j++) {
                sb.append("    ");
            }
            String trim = sb.toString();
            useClassReport.setNum(trim+useClassReport.getNum());
            useClassReport.setLevel(level.toString());
            Integer inUse = 0;
            //    闲置
            Integer idle = 0;
            //    待发放
            Integer give = 0;
            //    借用
            Integer borrow = 0;
            //    已报废
            Integer scrapped = 0;
            //    调拨中
            Integer transfer = 0;
            //    维修中
            Integer repair = 0;
            //    总计
            Integer total = 0;
            for (UseClassReport ucr : reportList) {
                String  treecode = ucr.getTreecode();
                ucr.setInUse(ucr.getInUse()==null? 0 : ucr.getInUse());
                ucr.setIdle(ucr.getIdle()==null? 0 : ucr.getIdle());
                ucr.setGive(ucr.getGive()==null? 0 : ucr.getGive());
                ucr.setBorrow(ucr.getBorrow()==null? 0 : ucr.getBorrow());
                ucr.setScrapped(ucr.getScrapped()==null? 0 : ucr.getScrapped());
                ucr.setTransfer(ucr.getTransfer()==null? 0 : ucr.getTransfer());
                ucr.setRepair(ucr.getRepair()==null? 0 : ucr.getRepair());
                ucr.setTotal(ucr.getTotal()==null? 0 : ucr.getTotal());
                //如果是根节点到子节点相加
                if (treecode.contains(useClassReport.getId())){
                    inUse += ucr.getInUse();
                    //    闲置
                    idle += ucr.getIdle();
                    //    待发放
                    give += ucr.getGive();
                    //    借用
                    borrow += ucr.getBorrow();
                    //    已报废
                    scrapped += ucr.getScrapped();
                    //    调拨中
                    transfer += ucr.getTransfer();
                    //    维修中
                    repair += ucr.getRepair();
                    //    总计
                    total += ucr.getTotal();
                    continue;
                }
            }
            useClassReport.setInUse(inUse);
            useClassReport.setIdle(idle);
            useClassReport.setGive(give);
            useClassReport.setBorrow(borrow);
            useClassReport.setScrapped(scrapped);
            useClassReport.setTransfer(transfer);
            useClassReport.setRepair(repair);
            useClassReport.setTotal(total);
        }
        return  reportList;
    }

    public  List<ClassIncreaseDecrease> classIncreaseDecrease(ClassInDeParam param){
        String token = request.getHeader("token");
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String orgId = cacheUtils.getUserCompanyId(token);
        List<LoginRole> loginRoles = loginUser.getLoginRoles();
        List<String> roles = loginRoles.stream().map(LoginRole::getRoleLevel).collect(Collectors.toList());
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        param.setUserId(userId);
        param.setOrgId(orgId);
        List<ClassIncreaseDecrease> list = mapper.classIncreaseDecrease(param);
        return list;
    }

    public  List<ClassIncreaseDecrease> exportClassIncreaseDecrease(String token,ClassInDeParam param){
        LoginUser loginUser = cacheUtils.getUser(token);
        String userId = loginUser.getUserId();
        String orgId = cacheUtils.getUserCompanyId(token);
        List<LoginRole> loginRoles = loginUser.getLoginRoles();
        List<String> roles = loginRoles.stream().map(LoginRole::getRoleLevel).collect(Collectors.toList());
        Integer isAllData = reportMapper.selectUserIsAllDataAuth(userId);
        if(isAllData==1){
            userId = null;
        }
        param.setUserId(userId);
        param.setOrgId(orgId);
        List<ClassIncreaseDecrease> list = mapper.classIncreaseDecrease(param);
        return list;
    }

}
